package com.example.futureai.config;

import com.example.futureai.config.propertise.JedisPropertiseConfig;
import com.example.futureai.config.propertise.RedisPropertiesConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.ConnectionPoolConfig;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisPooled;

import java.net.URI;
import java.net.URISyntaxException;
import java.time.Duration;

/**
 * @ClassName: MyJedisPoolConfig
 * @Description:
 * @Author: YourName
 * @Date: 2025/2/24
 */

@Configuration
public class MyJedisPoolConfig {

    @Autowired
    private JedisPropertiseConfig jpc;

    @Autowired
    private RedisPropertiesConfig rpc;

    @Bean("springAiJedisPooled")
    public JedisPooled jedisPooled() throws URISyntaxException {
        ConnectionPoolConfig poolConfig = new ConnectionPoolConfig();
        // 池中最大活跃连接数，默认 8
        poolConfig.setMaxTotal(jpc.getMaxActive());
        // 池中最大空闲连接数，默认 8
        poolConfig.setMaxIdle(jpc.getMaxIdle());
        // 池中的最小空闲连接数，默认 0
        poolConfig.setMinIdle(jpc.getMinIdle());
        // 启用等待连接变为可用
        poolConfig.setBlockWhenExhausted(true);
        // 等待连接变为可用的最大秒数，jdk17 以上支持，低版本可用 setMaxWaitMillis
        poolConfig.setMaxWait(Duration.ofSeconds(1));
        // 控制检查池中空闲连接的间隔时间，jdk17 以上支持，低版本可用 setTimeBetweenEvictionRunsMillis
        poolConfig.setTimeBetweenEvictionRuns(Duration.ofSeconds(1));
        return new JedisPooled(poolConfig, new URI(rpc.getUrl()));
    }

    @Bean(name = "myJedisPool")
    public JedisPool jedisPool() {
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(jpc.getMaxActive());
        config.setMaxIdle(jpc.getMaxIdle());
        return new JedisPool(config, rpc.getHost(), rpc.getPort(), rpc.getTimeout());
    }
}


